package t5750.springcloudalibaba.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

import t5750.springcloudalibaba.service.RocketMqSenderService;
import t5750.springcloudalibaba.service.RocketMqSource;

@Service
public class RocketMqSenderServiceImpl implements RocketMqSenderService {
	@Autowired
	private RocketMqSource source;

	@Override
	public void send(String msg) throws Exception {
		source.output1().send(MessageBuilder.withPayload(msg).build());
	}

	@Override
	public <T> void sendWithTags(T msg, String tag) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put(MessageConst.PROPERTY_TAGS, tag);
		Message message = MessageBuilder.createMessage(msg, new MessageHeaders(
				map));
		source.output1().send(message);
	}

	@Override
	public <T> void sendObject(T msg, String tag) throws Exception {
		Message message = MessageBuilder
				.withPayload(msg)
				.setHeader(MessageConst.PROPERTY_TAGS, tag)
				.setHeader(MessageHeaders.CONTENT_TYPE,
						MimeTypeUtils.APPLICATION_JSON).build();
		source.output1().send(message);
	}

	@Override
	public <T> void sendTransactionalMsg(T msg, int num) throws Exception {
		MessageBuilder builder = MessageBuilder.withPayload(msg).setHeader(
				MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
		builder.setHeader("test", String.valueOf(num));
		builder.setHeader(RocketMQHeaders.TAGS, "binder");
		Message message = builder.build();
		source.output2().send(message);
	}
}